<template>
    <div class="brand-age-page">
      <!-- 顶部信息卡片 -->
      <div class="info-card">
        <div class="info-content">
          <div class="info-image">
            <img src="/banner2.jpg" alt="品牌销售分析（按年龄段）" />
          </div>
          <div class="info-text">
  <h2>📊 品牌销售分析（按年龄段）</h2>
  <p class="desc">
    本图通过对不同年龄段消费者的购买数据进行统计分析，展示了各年龄群体在主要电子产品类别上的消费偏好与行为差异。  
    <br /><br />
    从整体趋势来看，年轻群体在智能手机、耳机、平板电脑等个人电子设备上的购买比例较高，体现出他们对新兴科技产品的关注和需求；而中年及以上人群则更倾向于购买家用电器、厨房设备等实用型产品，消费决策更注重生活品质与家庭需求。  
    <br /><br />
    通过对这些数据的对比与分析，可以帮助品牌和商家更好地理解不同年龄层的消费习惯，从而在产品研发、市场推广和精准营销策略制定中做出更有针对性的决策。
  </p>
</div>

        </div>
      </div>
  
      <!-- 筛选器 -->
      <div class="filters">
        <label>
          年龄段：
          <select v-model="selectedAge">
            <option v-for="age in ageRanges" :key="age" :value="age">{{ age }}</option>
          </select>
        </label>
      </div>
  
      <!-- 柱状图 -->
      <div class="chart-card">
        <div ref="chartRef" class="chart-container"></div>
        <p class="note">横轴为品牌类别（中文），纵轴为总量</p>
      </div>
  
      <!-- 下载按钮 -->
      <div class="download-wrapper">
        <button class="download-btn" :disabled="!chartInstance" @click="downloadChart">
          下载图表文件
        </button>
      </div>
  
      <!-- 页面底部 -->
      <FooterInfo />
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, nextTick, watch } from 'vue'
  import * as echarts from 'echarts'
  import FooterInfo from '../components/FooterInfo.vue'
  import axios from 'axios'
  
  const chartRef = ref(null)
  const chartInstance = ref(null)
  
  // 年龄段选项
  const ageRanges = [
    '15-19', '20-24', '25-29', '30-34',
    '35-39', '40-44', '45-49', '50-55'
  ]
  const selectedAge = ref(ageRanges[0])
  
  // 接口数据原始存放
  const apiData = ref([])
  
  const API_BASE = 'http://localhost:8080/querySumCategory'
  
  /**
   * 映射表：英文完整类目 -> 中文展示名
   * （我已覆盖你示例数据里的常见项；如需调整或扩展，直接修改这里）
   */
   const categoryMap = {
  null: '其他',
  'electronics.smartphone': '智能手机',
  'computers.notebook': '笔记本电脑',
  'appliances.kitchen.refrigerators': '冰箱',
  'appliances.environment.vacuum': '吸尘器',
  'appliances.kitchen.kettle': '电热水壶',
  'computers.peripherals.mouse': '鼠标',
  'appliances.kitchen.washer': '洗碗机',
  'appliances.kitchen.hood': '油烟机',
  'appliances.kitchen.microwave': '微波炉',
  'appliances.iron': '电熨斗',
  'appliances.environment.air_conditioner': '空调',
  'appliances.personal.scales': '电子秤',
  'computers.network.router': '无线路由器',
  'computers.components.hdd': '硬盘',
  'computers.components.cpu': '处理器',
  'electronics.audio.headphone': '耳机',
  'electronics.video.tv': '电视',
  'appliances.kitchen.blender': '搅拌机',
  'stationery.battery': '电池'
}

  
  /**
   * 段映射（降级使用）：把单段英文转成中文
   */
  const segmentMap = {
    electronics: '电子',
    computers: '电脑',
    appliances: '家电',
    kitchen: '厨房',
    environment: '环境',
    personal: '个人',
    furniture: '家具',
    peripherals: '外设',
    network: '网络',
    video: '视频',
    audio: '音频',
    smartphone: '手机',
    notebook: '笔记本',
    refrigerators: '冰箱',
    washer: '洗衣机',
    kettle: '电水壶',
    table: '桌',
    hood: '油烟机',
    blender: '搅拌机',
    iron: '熨斗',
    microwave: '微波炉',
    air_conditioner: '空调',
    clocks: '钟表',
    tablet: '平板',
    scales: '体重秤',
    router: '路由器',
    mouse: '鼠标',
    headphone: '耳机',
    tv: '电视'
  }
  
  /**
   * 将英文类目映射为中文展示名（fallback 逻辑：按段映射并用 · 连接）
   */
  function mapCategoryName(cat) {
    if (cat === null || cat === undefined) return '其他'
    if (categoryMap.hasOwnProperty(cat)) return categoryMap[cat]
    // 降级：按 '.' 切分并使用 segmentMap 映射，替换下划线
    const parts = cat.split('.')
    const mapped = parts.map(p => {
      // 一般像 air_conditioner 带下划线的先替换为 _ 再查找
      if (segmentMap[p]) return segmentMap[p]
      const normalized = p.replace(/_/g, ' ')
      if (segmentMap[normalized]) return segmentMap[normalized]
      // 如果无法映射，尝试把下划线换成空格并首字母大写；否则直接返回原串
      return normalized
    })
    return mapped.join('·')
  }
  
  async function fetchData() {
    try {
      const { data: res } = await axios.get(API_BASE, {
        params: { age: selectedAge.value }
      })
      apiData.value = res && res.code === 200 ? res.data : []
      updateChart()
    } catch (err) {
      console.error('请求失败：', err)
      apiData.value = []
      updateChart()
    }
  }
  
  /*把原始数据按映射后名称聚合（相同中文名合并）*/
  function buildAggregatedSeries(raw) {
    const agg = new Map()
    raw.forEach(item => {
      const origCat = item.category === undefined ? null : item.category
      const disp = mapCategoryName(origCat)
      const prev = agg.get(disp) || 0
      const addVal = Number(item.sum) || 0
      agg.set(disp, prev + addVal)
    })
    // 排序：按数值降序（可按需改）
    const entries = Array.from(agg.entries()).sort((a, b) => b[1] - a[1])
    const categories = entries.map(e => e[0])
    const sums = entries.map(e => e[1])
    return { categories, sums }
  }
  
  function updateChart() {
    if (!chartInstance.value) return
  
    if (!apiData.value || apiData.value.length === 0) {
      chartInstance.value.clear()
      return
    }
  
    const { categories, sums } = buildAggregatedSeries(apiData.value)
  
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: params => {
          // params 为数组，取第0项
          if (!params || params.length === 0) return ''
          const p = params[0]
          return `${p.name}<br/>总量: ${Number(p.value).toLocaleString()}`
        }
      },
      title: {
        text: `${selectedAge.value} 岁年龄段品牌总量分布`,
        left: 'center',
        top: 0
      },
      xAxis: {
        type: 'category',
        data: categories,
        axisLabel: {
          rotate: 30,
          interval: 0,
          fontSize: 12,
          formatter: function (value) {
            if (value.length > 12) {
              return value.slice(0, 12) + '...'
            }
            return value
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '总量'
      },
      grid: {
        left: '6%',
        right: '6%',
        bottom: '22%',
        containLabel: true
      },
      series: [
        {
          name: '总量',
          type: 'bar',
          data: sums,
          label: {
            show: true,
            position: 'top',
            formatter: '{c}'
          },
        }
      ]
    }
  
    chartInstance.value.setOption(option)
  }
  
  onMounted(async () => {
    await nextTick()
    if (!chartRef.value) return
    chartInstance.value = echarts.init(chartRef.value)
    fetchData()
  
    window.addEventListener('resize', () => {
      chartInstance.value && chartInstance.value.resize()
    })
  })
  
  watch(selectedAge, () => {
    fetchData()
  })
  
  function downloadChart() {
    if (!chartInstance.value) return
    const url = chartInstance.value.getDataURL({
      type: 'png',
      pixelRatio: 2,
      backgroundColor: '#fff'
    })
    const link = document.createElement('a')
    link.href = url
    link.download = `brand-sales-${selectedAge.value}.png`
    link.click()
  }
  </script>
  
  <style scoped>
  .brand-age-page {
    max-width: 1000px;
    margin: 40px auto;
    font-family: 'Segoe UI', sans-serif;
  }
  
  .info-card {
    background: #fff;
    padding: 25px 30px;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    margin-bottom: 25px;
  }
  .info-content {
    display: flex;
    align-items: flex-start;
    gap: 20px;
  }
  .info-image img {
    width: 240px;
    height: auto;
    border-radius: 8px;
    object-fit: cover;
    margin-top: 70px;
  }
  .info-text {
    flex: 1;
  }
  .info-text h2 {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 12px;
    color: #333;
  }
  .info-text .desc {
    font-size: 15px;
    color: #555;
    line-height: 1.8;
    text-align: justify;
  }
  
  .filters {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
  }
  .filters label {
    font-size: 14px;
    color: #333;
  }
  .filters select {
    margin-left: 6px;
    padding: 4px 8px;
  }
  
  .chart-card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    padding: 20px;
    margin-bottom: 20px;
  }
  .chart-container {
    width: 100%;
    height: 500px;
  }
  .note {
    text-align: center;
    font-size: 13px;
    color: #888;
    margin-top: 10px;
  }
  
  .download-wrapper {
    text-align: center;
    margin-bottom: 30px;
  }
  .download-btn {
    background: #5470C6;
    color: #fff;
    padding: 10px 22px;
    border: none;
    border-radius: 6px;
    font-size: 15px;
    cursor: pointer;
    transition: background 0.3s;
  }
  .download-btn:hover {
    background: #3b5ba4;
  }
  .download-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
  }
  </style>
  